﻿package de.gameduell.framework.facebook.app.popups {
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.None;
	import fl.transitions.easing.Regular;

	import de.gameduell.framework.gui.animation.CombinedTween;
	import de.gameduell.framework.gui.animation.GDTween;
	import de.gameduell.framework.gui.animation.PositionTween;
	import de.gameduell.framework.gui.animation.ScaleTween;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;

	public class CoinsCollectedPopup extends PyramidBasePopup {
		private var coin:Sprite;
		private var targetPos:Point;

		public function CoinsCollectedPopup(coinTargetPos:Point) {
			super("coinsCollectedPopup", "coinsCollectedPopup", 0, false);
			blocker.setColor(0x000000, 0);
			_position.x -= 10;
			
			localeData.setValue("collectedCoins", String(controller.lastGameResult.collectedCoins));
			targetPos = coinTargetPos;			
			
			_position.y = layout.contentPosition.y + 50;
			
//			show();
//			var hideTimer:Timer = new Timer(500, 1);
//			hideTimer.addEventListener(TimerEvent.TIMER_COMPLETE, animateCoin);
//			hideTimer.start();
		}
		
		override public function show(event:Event = null):void {
			super.show();
			var hideTimer:Timer = new Timer(500, 1);
			hideTimer.addEventListener(TimerEvent.TIMER_COMPLETE, animateCoin);
			hideTimer.start();
		}
		
		private function animateCoin(event:Event):void {
			if(controller.lastGameResult.collectedCoins > 0){
				coin = sprite.getChildByName("coinAnimation") as Sprite;
				var startPos:Point = new Point(coin.x, coin.y);
				var endPos:Point = globalToLocal(new Point(targetPos.x, targetPos.y-5));
				var tween:CombinedTween = new CombinedTween();
				tween.addTween(new PositionTween(coin, Regular.easeInOut, startPos, endPos, 1, true));
				tween.addTween(new ScaleTween(coin, Regular.easeInOut, 1, 0.25 , 1.5, true));
				tween.addTween(new GDTween(coin, "alpha", None.easeNone, 1, 0 , 1.6, true));
				
				tween.addEventListener(TweenEvent.MOTION_FINISH, onAnimDone);
				tween.start();
			}else{
				var hideTimer:Timer = new Timer(1000, 1);
				hideTimer.addEventListener(TimerEvent.TIMER_COMPLETE, hide);
				hideTimer.start();
			}
		}
		
		private function onAnimDone(event:TweenEvent):void {
			coin.visible = false;
			controller.gameData.coins = controller.gameData.coins + controller.lastGameResult.collectedCoins;
			hide();
		}
	}
}
